package com.zgy.myshellcommand.command;

import com.zgy.myshellcommand.anno.CommandConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.shell.CompletionProposal;
import org.springframework.shell.command.CommandRegistration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;

@CommandConfig
public class CommandTest {


    @Bean
    public CommandRegistration add(){
        return CommandRegistration.builder()
                .command("add")
                .hidden()
                .description("计算所有参数的和")
                .group("math")
                .withAlias()
                    .command("sum")
                    .and()
                .withOption()
                .longNames("ex")
                .and()
                .withOption()
                    .longNames("args")
                    .shortNames('a')
                    .type(ArrayList.class)
                    .arity(CommandRegistration.OptionArity.ONE_OR_MORE)
                .completion(ctx -> {
                    return Arrays.asList("a", "args").stream()
                            .map(CompletionProposal::new)
                            .collect(Collectors.toList());
                })
                    .and()
                .withTarget()
                    .function(ctx-> {
//                        ArrayList<String> args = ctx.getOptionValue("a");
//                        return args.stream().map(Double::parseDouble).reduce((a,b)->a+=b).get();
                    if (ctx.getOptionValue("ex")==null){
                        return 1;
                    }
                    return 2;
                    })
                    .and()
//                .withErrorHandling()
//                    .resolver(ex->{
//                        if (ex instanceof NumberFormatException) {
//                            return CommandHandlingResult.of("数据格式异常,确认是否传入非数据类型的参数\n", 100);
//                        }
//                        return CommandHandlingResult.of(ex.getMessage());
//                    })
//                    .and()
//                .withExitCode()
//                    .map(ex -> ex instanceof NumberFormatException?100:101)
//                    .and()
                .withHelpOptions()
                    .enabled(true)
                    .longNames("help")
                    .shortNames('h')
                    .and()
                .build();
    }


}
